%Goal: mortgage market equilibrium

%INPUTS:
%alpha: household price sensitivity
%F: total mortgage face value
%Nb: number of local banks
%No: number of non-local banks
%Nn: number of shadow banks
%qn: shadow bank mortgage quality 
%qb: bank mortgage quality
%psi: bank funding cost
%rhon: common component of shadow bank funding cost
%eta: warehouse duration
%sigma_xi: volatility of shadow bank idiosyncratic taste shock
%co: non-local bank marginal cost of warehouse lending
%cb: local bank marginal cost of warehouse lending
%shadow bank idiosyncratic taste shock






function [rno, sno, rnbl,snbl] = Solve_profit_local(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob,rhobl,sow,sbw,rb,rbl,rm,rnb)
%% set up the solution to the model

%%% household preference shock grid and transition matrix 
MaxIterations=10000;
tol = 10^(-9);
rnbl_initial = 1.85;
rnbl = [];
diff = 1000;
iter = 0;

while diff>tol && iter<=MaxIterations  
        iter = iter+1;
       [rno,sno] = Solve_profit_nonlocal(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob,rhobl,sow,sbw,rb,rbl,rm,rnb,rnbl_initial);
        snbl =  exp(-alpha*rnbl_initial+qn)/(1+exp(-alpha*rbl+qb)+(Nb-1)*exp(-alpha*rb+qb)+Nm*exp(-alpha*rm+qb)+Nn*sow*exp(-alpha*rno+qn)+Nn*sbw*exp(-alpha*rnbl_initial+qn)+Nn*sbw*(Nb-1)*exp(-alpha*rnb+qn));
        rnbl =  eta*rhobl+k+1/(alpha*(1-snbl));
        diff = abs(rnbl-rnbl_initial);
        rnbl_initial = rnbl;
        

        

end
end 
